<?php

namespace Rblog\Module\Admin\Model;

class Comment extends \Rexzy\App\Model {

    protected $_table = 'comment';
    
    
    /**
     * 查询一组文章里每篇文章的评论量
     * 
     * @param array() $arts 包含要查询的文章的信息的数组
     * @return array()
     */
    public function getEACNum( $arts ) {
        foreach ( $arts as $key => $val ) {
            $where = array( 'artid' => $val['artid'] );
            $arts[$key]['comment'] = $this->select( 'count(*)', $where )['count(*)'];
        }
        
        return $arts;
    }
    
    /**
     * 获取评论列表
     * 
     * @param array $condition 查询条件
     * @param int $start 开始取的位置
     * @param int $length 获取评论的量
     */
    public function getList( $condition, $start = 0, $length = 100000 ) {
        $filed = 'rblog_comment.commentid, rblog_comment.name, rblog_comment.date, rblog_comment.content, rblog_comment.artid, rblog_comment.email';
        
        if ( ( ! empty( $condition ) ) && ( isset( $condition['search'] ) ) ) {
            $where = "left join rblog_arts on rblog_comment.artid = rblog_arts.artid where rblog_comment.name like ? or rblog_comment.date like ? or rblog_comment.content like ? or rblog_arts.title like ?";
            $where .= "group by commentid order by commentid desc"; 
        } else {
            $where = " group by commentid order by commentid desc";
        }
        $params = array();
        if ( ! empty( $condition ) ) {
            $param =  "%" . $condition['search'] . "%";
            $params = array( $param, $param, $param, $param );
        } 
        $limit = $start . ', ' . $length; 
        $comments = $this->selectAll( $filed, $where, $limit, $params );
        
        $artData = \Rexzy::model( 'Arts' );
        foreach( $comments as $key => $val ) {
            $artTitle = $artData->select( 'title', array( 'artid' => $val['artid'] ) )['title'];
            $comments[$key]['title'] = $artTitle;
            $comments[$key]['date'] = date( 'Y-m-d', $val['date'] );
        }
        return $comments;
    }
    
    /**
     * 删除评论
     * 
     * @param array $commentid 需要删除的评论id
     * @return int 删除评论的量
     */
    public function del( $commentid ) {
        $params = array();
        $wherestr = array();
        foreach( $commentid as $key => $val ) {
            $params[] = $val;
            $wherestr[] = "commentid = ?";
        }
        $where = implode( ' or ', $wherestr );
        
        $result = $this->delete( $where, $params );
        return $result;
    }
}
